package android.crosstime.utils;

import java.io.File;
import java.io.IOException;

import android.content.ContentResolver;
import android.content.Context;
import android.content.res.Resources;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.net.Uri;
import android.os.Environment;
import android.os.StatFs;
import android.provider.MediaStore;
import android.provider.MediaStore.Images;

public class JUtils {
	
	public JUtils() {
	}
	
	
	public static Bitmap getThumbnail(ContentResolver cr, long origId) {
		BitmapFactory.Options options = new BitmapFactory.Options();
		options.inDither = false;
		options.inPreferredConfig = Bitmap.Config.RGB_565;

		return Images.Thumbnails.getThumbnail(cr, origId,
				Images.Thumbnails.MINI_KIND, options);
	}

	public static boolean hasStorage(boolean requireWriteAccess) {
		String state = Environment.getExternalStorageState();

		if (Environment.MEDIA_MOUNTED.equals(state)) {
			if (requireWriteAccess) {
				boolean writable = checkFsWritable();
				return writable;
			} else {
				return true;
			}
		} else if (!requireWriteAccess	&& Environment.MEDIA_MOUNTED_READ_ONLY.equals(state)) {
			return true;
		}
		return false;
	}
	
	private static boolean checkFsWritable() {
		// Create a temporary file to see whether a volume is really writable.
		// It's important not to put it in the root directory which may have a
		// limit on the number of files.
		String directoryName = Environment.getExternalStorageDirectory().toString() + "/DCIM/Camera";
		File directory = new File(directoryName);
		if (!directory.isDirectory()) {
			if (!directory.mkdirs()) {
				return false;
			}
		}
		File file = new File(directoryName, ".probe");
		try {
			if (file.exists()) {
				file.delete();
			}
			if (!file.createNewFile()) {
				return false;
			}
			file.delete();
			return true;
		} 
		catch (IOException ex) {
			return false;
		}
	}
	
	/** Unit:KB */
	public static long getSDCardAvailableSize()
	{
		try {
	        if (!hasStorage(true)) {
	            return -1;
	        } 
	        else {
	            String storageDirectory = Environment.getExternalStorageDirectory().toString();
	            StatFs stat = new StatFs(storageDirectory);
	            float freespace = (float) stat.getAvailableBlocks() * stat.getBlockSize();
	            return (long) (freespace / 1024);
	        }
	    } 
		catch (Exception ex) {
	        return -1;
	    }
	}
	
	public static boolean isVideoUri(Uri uri)
	{
		if(uri != null)
		{
			String uriString = uri.toString();
			if ( uriString.startsWith(MediaStore.Video.Media.EXTERNAL_CONTENT_URI.toString())) 
			{
				return true;
			}
			else if (uriString.startsWith(MediaStore.Video.Media.INTERNAL_CONTENT_URI.toString()))
			{
				return true;
			}
		}
		return false;
	}
	
	public static boolean isMediaScannerScanning(Context context) {
        boolean result = false;
        if(context == null)
        	return result;
        Cursor cursor = MediaScannerStatusQuery(context, MediaStore.getMediaScannerUri(),
                new String [] { MediaStore.MEDIA_SCANNER_VOLUME }, null, null, null);
        if (cursor != null) {
            if (cursor.getCount() == 1) {
                cursor.moveToFirst();
                result = "external".equals(cursor.getString(0));
            }
            cursor.close();
        }
        return result;
    }
	
	public static Cursor MediaScannerStatusQuery(Context context, Uri uri, String[] projection,
            String selection, String[] selectionArgs, String sortOrder) {
        try {
            ContentResolver resolver = context.getContentResolver();
            if (resolver == null) {
                return null;
            }
            return resolver.query(uri, projection, selection, selectionArgs, sortOrder);
         } catch (UnsupportedOperationException ex) {
            return null;
        }
    }
	
	public static boolean getRoot() {
		boolean preIsRoot = false;
		try {
			if (LinuxShell.isRoot(Runtime.getRuntime(), 50)){
				preIsRoot = true;
			} else {
				preIsRoot = false;
			}
		} catch (IOException e) {
			e.printStackTrace();
			preIsRoot = false;
		} catch (InterruptedException e) {
			e.printStackTrace();
			preIsRoot = false;
		}
		return preIsRoot;
	}
	
	public static Bitmap rotateBmp(Context context, int srcId, int angle)
	{
		Resources res = context.getResources();
        Bitmap img = BitmapFactory.decodeResource(res, srcId);
        Matrix matrix = new Matrix(); 
        matrix.postRotate(angle); 
        int width = img.getWidth();
        int height = img.getHeight();
        return Bitmap.createBitmap(img, 0, 0, width, height, matrix, true);
	}
	
}
